from Config import ConfigController
from Logger import Logger
import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


# from email import encoders

class EmailController:
    def __init__(self, configPath="../Config/config.ini", loggerConfigPath="../Logger/logging.json"):
        # self.__configPath = "../Config/config.ini"
        # self.__loggerConfigPath = ".. /Logger/logging.json"
        # print(self.__configPath)
        # print(self.__loggerConfigPath)
        # self.config = ConfigController.ConfigController(self.__configPath)
        self.config = ConfigController.ConfigController(configPath)
        # self.logger = Logger(self.__loggerConfigPath)
        self.__user = self.config.getConfig(sectionName="EMAIL",
                                            optionName="user_name")
        self.__passwd = self.config.getConfig(sectionName="EMAIL",
                                              optionName="password")
        self.__smtpAddr = self.config.getConfig(sectionName="EMAIL",
                                                optionName="smtp")
        self.__loggerConfigPath = loggerConfigPath

    def sendEmail(self, toAddr="ina@tju.edu.cn", msgStr="", subject="", withLog=True):
        user = self.__user
        pwd = self.__passwd
        msg = MIMEMultipart()
        msg['Subject'] = subject
        content = MIMEText(msgStr, 'plain', 'utf-8')
        msg.attach(content)
        smtpServer = smtplib.SMTP(self.__smtpAddr)
        try:
            smtpServer.login(user, pwd)
            flag = smtpServer.sendmail(user, toAddr, msg.as_string())
            # return flag
            if flag is not None:
                return flag
        except Exception as e:
            # print(e)
            if withLog:
                logger = Logger.Logger(self.__loggerConfigPath)
                logger.fileInfoLogger.error("Error from EmailController: %s" % (e))
            return False
        finally:
            smtpServer.close()


if __name__ == '__main__':
    ec = EmailController()
    print(ec.sendEmail("ina@tju.edu.cn", "TestEmail"))
